/**
 * problem_004.c
 * Copyright (C) 2011-03-17 - xrose
 * The largest palindrome made from the product of two 3-digit numbers?
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int isPalin(char *numb);
char* itoa(int value, char* result, int base);
int main (int argc, char *argv[])
{
    int i, j, prod, maxprod =0;
    char buff[8];
    for(i=100; i<=999; i++)
    {
        for(j=100; j<=999; j++)
        {
            prod = i*j;
            itoa(prod, buff, 10);
            if(isPalin(buff))
            {
                if(prod > maxprod)
                {
                        maxprod = prod;
                }
            }
        }
    }
    printf("The largest palindrome made from the product of two 3-digit numbers is: %d\n", maxprod);
    return 0;
}

char* itoa(int value, char* result, int base) {
    // check that the base if valid
    if (base < 2 || base > 36) { *result = '\0'; return result; }

    char* ptr = result, *ptr1 = result, tmp_char;
    int tmp_value;

    do {
        tmp_value = value;
        value /= base;
        *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
    } while ( value );

    // Apply negative sign
    if (tmp_value < 0) *ptr++ = '-';
    *ptr-- = '\0';
    while(ptr1 < ptr) {
        tmp_char = *ptr;
        *ptr--= *ptr1;
        *ptr1++ = tmp_char;
    }
    return result;
	}
int isPalin(char *numb)
{
    int top, bottom;
    top =0;
    bottom = strlen(numb) -1;
    while((bottom>=top) && (numb[top] == numb[bottom]))
    {
        top++;
        bottom--;
    }
    return (top>=bottom ? 1:0);
}
